import { connection } from "../app/database/mysql";
import { getInfoByIdAndType } from "../corner/common.service";
import { getUserById } from "../user/user.service";
import { createUserAuth, selectUserAuth, userAuthUpdate } from "../user_auth/user_auth.service";
import { paymentModel, targetPriceModel } from "./order.model";


/**
 * 支付
 */
export const getPayments = async (orderData: paymentModel) => {
  // 准备查询
  const statement = `
    INSERT INTO \`order\`
    SET ?
  `;

  // 执行查询
 try {
   const [data] = await connection.promise().query(statement, orderData);
   // 提供数据
   return data;
 }catch (error) {
   console.log(error.message);
 }
 return null
};

/**
 * 按 ID 获取订单
 */
export const getOrderById = async (orderId: string) => {
  // 准备查询
  const statement = `
    SELECT * FROM \`order\`
    WHERE out_trade_no = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, orderId);

  // 提供数据
  return data as any;
}

/**
 * 已收到付款
 */
export const paymentRecived = async (orderId: string, paymentResult: any) => {
  // 检查订单
  const [order] = await getOrderById(orderId);
  const isValidOrder = order && order.status == 0;
  
  if (!isValidOrder) return;

  // 更新订单状态
  await updateOrder(order.out_trade_no, { status: 1 } as any);
  const [userData] = await getOrderById(orderId);
  let total_fee = userData.total_fee / 100;
  const [vip_days] = await getByPriceTargetPrices(total_fee);

  // 按用户 ID 查询内容
  let isUserAuthId = await selectUserAuth(userData.user_id);

  // let startTime = parseInt(`${new Date().getTime() / 1}`, 10);
  // let endTime = parseInt(`${startTime + 86400000 * vip_days.vip_day}`, 10)
  let startTime = Date.now();  // 等同于 new Date().getTime()
  let endTime = startTime + 86400000 * vip_days.vip_day;
  const post = { user_id: userData.user_id, vip_days: vip_days.vip_day, startTime: startTime, endTime: endTime }

  if (Object.keys(isUserAuthId).length !== 0 && isUserAuthId[0].user_id && isUserAuthId[0].user_id > 0) {
    await userAuthUpdate(parseInt(`${userData.user_id}`, 10), post);

  } else {
    await createUserAuth(post);
  }
};

/**
 * 更新订单状态
 */
const updateOrder = async (orderId: string, status: number) => {
  // 准备查询
  const statement = `
    UPDATE \`order\`
    SET ?
    WHERE out_trade_no = ?
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, [status ,orderId]);

  // 提供数据
  return data;
};

/**
 * 创建类目价格
 */
export const createTargetPrice = async (targetPriceModel: targetPriceModel) => {
  // 准备查询
  const statement = `
    INSERT INTO target_price
    set ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, targetPriceModel);

  // 提供数据
  return data as any;
};

/**
 * 更新类目价格
 */
export const updateTargetPrice = async (postId: number, post: any) => {
  // 准备查询
  const statement = `
    UPDATE target_price
    SET ?
    WHERE id = ?
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data as any;
};

/**
 * 删除类目价格
 */
export const deleteTargetType = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM target_price
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data as any;
};

/**
 * 获取价格
 */
export const getTarget_prices = async () => {
  // 准备查询
  const statement = `
    SELECT * FROM target_price ORDER by id DESC
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement);

  // 提供数据
  return data as any;
};

/**
 * 条件获取价格
 */
export const getByPriceTargetPrices = async (price: any) => {
  // 准备查询
  const statement = `
    SELECT * FROM target_price WHERE price = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, price);

  // 提供数据
  return data as any;
};

/**
 * 按关键字获取（模糊查询）
 */
export const byKeyWordSelect = async (keyWord: any) => {
  // 准备查询
  const statement = `
    SELECT * FROM \`order\`
    WHERE (user_id = '${keyWord}' or out_trade_no LIKE '%${keyWord}%')
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, keyWord);

  let arr = []
  for (let item of data as any) {
    let res = await getInfoByIdAndType(item.commodity_id, item.commodity_type)
    if (!res) continue;
    item.data = res;
    arr.push(item);
  }

  // 提供数据
  return arr;
}

/**
 * 按ID获取价格
 */
export const getPrice = async (commodity_type: number) => {
  // 准备查询
  const statement = `
    SELECT price FROM target_price
    WHERE target_type = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, commodity_type);

  // 提供数据
  return data as any;
};

/**
 * 获取订单
 */
export const getOrder = async (pageSize: number, pageNo: number, status: number, user_id: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS * FROM \`order\`
  `;
  let where = []
  if (status >= 0) {
    where.push(`status = ` + status)
  }
  if (user_id > 0) {
    where.push(`user_id = ` + user_id)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }
  
  statement += ` ORDER by id DESC, id DESC limit ` + (pageNo > 0 ? (pageNo - 1) * pageSize : 0) + `,` + pageSize

  // 执行查询
  const [data] = await connection.promise().query(statement);
  
  let totalStatement = `SELECT FOUND_ROWS() as total`;
  const [result] = await connection.promise().query(totalStatement)
  let totalCount = result[0].total
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize
  
  for (let item of data as any) {
    let vip_type = await byPriceGetType(item.commodity_type) // 订单类型【日，周，月，年会员】
    
    let vipTime = vip_type[0] ? vip_type[0].vip_day * 86400000 : 0; // 计算会员时间（天数）
    let releaseTime = parseInt(item.releaseTime, 10); // 购买会员时间
    let newTime = Math.floor(new Date().getTime() / 1); // 获取目前时间

    // 判断是否过期 【 isValid: 1 (有效并且有效天大于1天)， isValid: 0 (无效)， isValid: 2 (有效并且有效天小于1天) 】
    if (newTime < parseInt(`${vipTime}`, 10) + releaseTime && item.status == 1) {
      item.isValid = 1;
    } else if (parseInt(`${vipTime}`, 10) + releaseTime - newTime < 86400000 && item.status == 1) {
      item.isValid = 2;
    } else {
      item.isValid = 0;
    }

    let endTime = releaseTime + parseInt(`${vipTime}`,10);
    item.endTime = endTime; // 到期时间
    item.orderType = vip_type // 订单类型【日，周，月，年会员】
    item.user = await getUserById(item.user_id) // 订单用户信息
    
  }
  let res = {
    data,
    totalPage,
    totalCount
  }

  // 提供数据
  return res;
};

/**
 * 获取用户订单
 */
export const getUserOrder = async (
  userId: number,
  status: number,
  commodity_id: number,
  commodity_type: number,
) => {
  // 准备查询
  const statement = `
    SELECT * FROM \`order\`
    WHERE
    user_id = ? AND
    status = ? AND
    commodity_id = ? AND
    commodity_type = ?
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, [userId, status, commodity_id, commodity_type]);

  // 提供数据
  return data;
};

/**
 * 按 ID 获取类目
 */
export const getByUserIdOrder = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM \`order\`
    WHERE user_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data as any;
};

/**
 * 按 ID 获取会员属性
 */
const getType = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM target_price
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data as any;
};

/**
 * 按 价格 获取会员属性
 */
const byPriceGetType = async (price: any) => {
  // 准备查询
  const statement = `
    SELECT * FROM target_price
    WHERE target_type = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, price);

  // 提供数据
  return data as any;
};
